using System;
using System.Security.Cryptography;

namespace CCSService_WebRole
{
	/// <summary>
	/// This class is the reply sent from the licensing server to a client
	/// in response to a validated license request.
	/// </summary>
	[Serializable]
	public class LicenseResponse : License
	{
		/// <summary>
		/// Default constructor
		/// </summary>
		public LicenseResponse()
		{
		}

		/// <summary>
		/// Special contstructor for initializing a license response object
		/// from the client, based on authentication information provided out 
		/// of band.
		/// </summary>
		/// <param name="product">Product string name</param>
		/// <param name="licenseLevel">Confirmed license level</param>
		/// <param name="clientIdentity">Unique client identity</param>
		/// <param name="authenticatedLicenseString">Authenticated license string</param>
		public LicenseResponse(
			string product,
			string licenseLevel,
			string clientIdentity,
			string authenticatedLicenseString)
		{
			ComputeClientIdentity(licenseLevel, product, clientIdentity);

			base.AuthenticatedLicense = Convert.FromBase64String(
				authenticatedLicenseString);
		}

		/// <summary>
		/// Encode the authenticated portion of a license (i.e. the digital 
		/// signature) as a hex string. 
		/// </summary>
		/// <returns>Authenticated license string</returns>
		public string GetAuthenticatedLicenseAsString()
		{
			return Convert.ToBase64String(base.AuthenticatedLicense);
		}

		/// <summary>
		/// Sign/certify the license  
		/// </summary>
		/// <param name="request">License request object</param>
		/// <param name="rsa">Provider context for server private key</param>
		public void Initialize(
			License request,
			RSACryptoServiceProvider rsa)
		{
			ClientIdentity = request.ClientIdentity;
            LicenseLevel = request.LicenseLevel;
			Product = request.Product;

			CertifyLicense(rsa);
		}

		/// <summary>
		/// Check the signature on the license 
		/// </summary>
		/// <param name="serverPublicKey">Server public key</param>
		/// <returns>Authenticated license level</returns>
		public string VerifyLicenseResponse(string serverPublicKey)
		{
			return VerifyLicense(serverPublicKey);
		}
	}
}